package dept

import (
	"context"
	"go-zero-project/common/excption"
	"go-zero-project/services/user/rpc/constans"
	"go-zero-project/services/user/rpc/internal/mapper"
	"go-zero-project/services/user/rpc/internal/svc"
	"go-zero-project/services/user/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type InfoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeptInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InfoLogic {
	return &InfoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *InfoLogic) DeptInfo(in *pb.DeptInfoReq) (*pb.DeptInfoResp, error) {
	// 1.query dept info by deptId
	deptMapper := mapper.NewDeptMapper()
	deptEntity, err := deptMapper.SelectOneForParentName(l.svcCtx.DBEngin, in.DeptId)
	if err != nil {
		return nil, err
	}
	if deptEntity.DeptId < 1 {
		return nil, excption.NewErrCode(constans.DeptNoExistError)
	}
	// 2.query dept sub
	selectSubCount, err := deptMapper.SelectSubCount(l.svcCtx.DBEngin, []int64{in.DeptId})
	if err != nil {
		return nil, err
	}
	// 3.return obj
	resp := &pb.DeptInfoResp{
		DeptId:     deptEntity.DeptId,
		Name:       deptEntity.Name,
		ParentId:   deptEntity.ParentId,
		ParentName: deptEntity.ParentName,
		OrderNum:   int32(deptEntity.OrderNum),
	}
	if len(selectSubCount) < 1 {
		return resp, nil
	}
	resp.SubNodeNum = selectSubCount[0].Count
	return resp, nil
}
